class ProfileController {

    def index = {
        redirect(action:"dashboard")
    }

    def dashboard = {
        // placeholder - results in dashboard view being rendered
    }

    def newProfile = {
        render(view:"create")
    }

    def create = {
        def user = User.get(session.user_id)

        def profile = new Profile("user": user)
        profile.properties = params
        user.addToProfiles(profile)
        if(!profile.hasErrors() && user.save()) {
            log.debug("${profile.user} has added a profile!")
            flash.message = "Congrats for adding a profile..."
            session.wedding_profile = true
            redirect(action:"dashboard")
        } else {
            flash.message = "There is a problem with your profile. Please review and correct the errors below..."
            render(view: "create", model: [profile:profile])
        }
    }

    def edit = {
        def profile = loadProfile()
        if(!profile) {
            log.debug("no profile found for user: ${session.user_id}")
            flash.message = "No profile found for user: ${session.user_id}"
            redirect(action:create)
        } else {
            return [profile : profile]
        }
    }

    def update = {
        def profile = loadProfile()
        if(profile) {
            profile.properties = params
            if(!profile.hasErrors() && profile.save()) {
                flash.message = "We've updated your profile."
                redirect(action:dashboard)
            }
            else {
                render(view:'edit',model:[profile:profile])
            }
        }
        else {
            flash.message = "Uh oh! We're not able to find your profile..."
            redirect(action:edit,id:params.id)
        }
    }

    def show = {
        def profile = loadProfile()
        render(view: "show", model: [profile:profile])
    }

    def loadProfile() {
        def profile
        def user = User.get(session.user_id)
        if(user) {
            profile = user.getWeddingProfile()
        }
        return profile
    }

}
